using System;
using Microsoft.SPOT;
using System.Collections;

namespace eHouse
{
    class IrrigationBL
    {
        private static IrrigationBL instance;

        public static IrrigationBL GetInstance()
        {
            if (instance == null)
                instance = new IrrigationBL();

            return instance;
        }

        public bool GetIrrigationState()
        {
            return Drivers.getInstance().led_irrigation.Read();
        }

        public void SetIrrigationState(bool state)
        {
            Drivers.getInstance().led_irrigation.Write(state);
        }

        public ArrayList GetRules()
        {
            ArrayList rulesList = new ArrayList();

            string irrigation_string = ConnectionManager.GetInstance().GetIrrigationRules();
            irrigation_string = irrigation_string.Substring("RULES_IRRIGATION/".Length);

            if (irrigation_string != "")
            {
                string[]irrigation_rules = irrigation_string.Split('|');

                foreach (string rule in irrigation_rules)
                {
                    if (rule != "")
                    {
                        Rule irrigationRule;
                        string[] rule_parts = rule.Split('\\');
                        string id = rule_parts[0];
                        string time = rule_parts[1];
                        bool state = rule_parts[2] == "TRUE";

                        irrigationRule = new Rule(id, state, time);
                        rulesList.Add(irrigationRule);
                    }
                }
            }

            return rulesList;
        }

        public void AddRule(Rule rule)
        {
            string ruleString = rule.ID;
            ruleString += "\\" + rule.Time + "\\";
            bool state = (bool)rule.Body;
            ruleString += state.ToString().ToUpper();

            ConnectionManager.GetInstance().AddIrrigationRules(ruleString);
        }

        public void DeleteRule(string guid)
        {
            ConnectionManager.GetInstance().DeleteIrrigationRule(guid);
        }
    }
}
